package org.framework.edge.builder.docker;

import lombok.extern.slf4j.Slf4j;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public abstract class AbstractDockerRuntime implements DockerRuntime {

    /**
     * 处理进程
     *
     * @param command 处理命令 <p>"docker", "ps", "-a"</p>
     */
    protected Result<?> doProcess(String... command) {
        try {
            // 创建一个ProcessBuilder实例
            ProcessBuilder processBuilder = new ProcessBuilder();
            // 设置命令和参数
            processBuilder.command(command);

            // 合并错误流和标准输出流（可选）
            processBuilder.redirectErrorStream(true);
            // 启动进程
            Process process = processBuilder.start();

            // 读取命令的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info(line);
            }

            // 等待进程结束
            int exitCode = process.waitFor();
            log.info("Exited with error code : {}", exitCode);
            return ResultFactory.successOf();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return ResultFactory.errorOf(e);
        }


    }
}
